package com.ric.controller.home;

import com.ric.dao.model.sysUser.SysUser;
import com.ric.service.sysuser.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * Created by ricteng on 2017/5/28.
 */
@Controller
@RequestMapping("/")
public class LoginController {
    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUserService sysUserService;

    /*
    * 初始化进入登录页面
    * */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin() {
        return "public/login";
    }

    /*
    * 系统登录
    * */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(SysUser user, Model model){
        String userName = user.getUserName();
        String password = user.getPassword();
        logger.debug("username => " + userName);
        logger.debug("password => " + password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        Subject subject = SecurityUtils.getSubject();
        String msg = null;
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            msg = e.getMessage();
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            msg = "密码不匹配(生产环境中应该写:用户名和密码的组合不正确)";
        } catch (LockedAccountException e){
            e.printStackTrace();
            msg = e.getMessage();
        }
        if(msg == null){
            //重定向
            return "redirect:/sys/user/logintest";
        }

        model.addAttribute("msg",msg);
        return "public/login1";
    }

}
